package com.example.dormmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormmanage.dao.IBuildingDao;
import com.example.dormmanage.dao.IStudentDao;
import com.example.dormmanage.entity.Building;
import com.example.dormmanage.entity.Room;
import com.example.dormmanage.entity.Student;
import com.example.dormmanage.service.IRoomService;
import com.example.dormmanage.service.IStudentService;
import com.example.dormmanage.util.CustomerException;
import com.example.dormmanage.util.JwtUtil;
import com.example.dormmanage.view.ResultView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class StudentService extends ServiceImpl<IStudentDao, Student> implements IStudentService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IRoomService roomService;

    //用户登录
    public ResultView studentLogin(Student student) {
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(student.getUserName(), student.getPassword());
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过,给出对应的提示
        if (authentication == null) {
            throw new CustomerException("用户名或密码错误");
        }
        LoginUser studentLoginUser = (LoginUser) authentication.getPrincipal();
        Map<String, String> map = new HashMap<>();
        //判断用户是否是第一次登录
        if (studentLoginUser.getStudent().getLastLoginTime() == null) {  //查询最新的登录时间,为空说明时第一次登录
            map.put("first", "1");
        }
        //记录此次登录时间
        LambdaUpdateWrapper<Student> lqw = new LambdaUpdateWrapper<>();
        lqw.eq(Student::getStudentId, studentLoginUser.getStudent().getStudentId())
                .set(Student::getLastLoginTime, LocalDateTime.now());
        this.update(lqw);
        //使用userId生成token
        String userId = studentLoginUser.getStudent().getStudentId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //把完整的用户信息存入redis
        map.put("token", jwt);
        map.put("username", studentLoginUser.getUsername());
        redisTemplate.opsForValue().set("login_student_" + userId, studentLoginUser, 600, TimeUnit.MINUTES);
        return ResultView.success(map);
    }

    //学生退出登录
    public ResultView<String> loginOutByStudent() {
        //获取SecurityContexHolder中的用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getStudent().getStudentId();
        //删除redis中的值
        redisTemplate.delete("login_student_" + id);
        return ResultView.success("退出成功");
    }

    //查询学生列表(根据不同楼宇)
    public ResultView<Page> selectStudentList(Integer buildingId, Integer page, Integer pageSize, String name) {
        Page<Student> pageInfo = new Page<>(page, pageSize);
        //查询宿舍列表
        LambdaQueryWrapper<Room> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Room::getBuildingId, buildingId)
                .orderByAsc(Room::getRoomName);
        List<Room> roomList = roomService.list(lqw);
        //查询每个楼宇对应的学生楼宇
        List<Student> studentList = new ArrayList<>();
        for (int i = 0; i < roomList.size(); i++) {
            LambdaQueryWrapper<Student> stuLqw = new LambdaQueryWrapper<>();
            stuLqw.like(name != null, Student::getRealName, name)
                    .eq(Student::getRoomId, roomList.get(i).getRoomId())
                    .orderByAsc(Student::getUserName);
            List<Student> studentList2 = this.list(stuLqw);
            studentList.addAll(studentList2);
        }
        pageInfo.setRecords(studentList);
        return ResultView.success(pageInfo);
    }


    //新增学生
    @Transactional(rollbackFor = Exception.class)
    public ResultView<String> addStudentData(Student student) {
        this.save(student);
        return ResultView.success("添加学生成功");
    }

    //删除学生
    public ResultView<String> deleteStudentData(Long id) {
        this.removeById(id);
        return ResultView.success("删除学生成功");
    }
}
